class Meeting < ActiveRecord::Base
	has_many :meeting_datas
	belongs_to :meeting_room
	belongs_to :employee
        validates_presence_of   :brief_desc 
  #validates_uniqueness_of :booking_date, :booking_time, :scope => :id , :message => "Occupied"
  attr_accessible :employee_id, :brief_desc, :full_desc, :booking_date, :booking_time, :duration, :meeting_room_id, :repeat_type, :repeat_end, :repeat_day, :repeat_weeks
  
  validate :check_cond, :on => :create, :unless => Proc.new {|meeting| meeting.id != nil}
  
  #before_save :check_free
  
	#after_create :create_meeting_data
	
	def check_free
	   errors.add_to_base("Room already booked") if Meeting.find_all_by_booking_date_and_booking_time(booking_date,booking_time).count >= 1
	end
	
	def check_cond
	  	  
	  room = MeetingRoom.find(meeting_room_id)
	  r = room.meetings.find_all_by_booking_date(booking_date)
	  arr = Array.new
    r.each do |myx|
     duration = myx.duration.to_i
      0.upto(duration-1) do |x|
        arr << myx.booking_time.hour+x
      end
    end  
    
    errors.add_to_base("Room already booked") if arr.include?booking_time.hour 
	end
	
	
	def create_meeting_data
	  #unless repeat_type == "none"
	  #	if repeat_type == "daily"
	  #		dur = repeat_end - booking_date
	  #		0.upto(dur) do |x| 
	  #		  meeting_datas.create(:meeting_id => id, :meeting_date => booking_date+x, :duration => duration, :meeting_time => booking_time+x.days, :booking_end => booking_time+duration.to_i.minutes+x.days )
	  #		end
	  #	end 
	  #else
			meeting_datas.create(:meeting_id => id, :meeting_date => booking_date, :duration => duration, :meeting_time => booking_time, :booking_end => booking_time+duration.to_i.minutes )
    #end
	end
end
